package com.java.common.boot.advice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.java.common.constant.ProjectConstants;
import com.java.common.lang.annotation.RichText;
import com.java.common.lang.domain.AjaxResult;
import com.java.common.lang.domain.ReturnVO;
import com.java.common.lang.exception.BaseException;
import com.java.common.utils.WebKit;
import com.java.common.utils.html.HtmlKit;

/**
 * 富文本响应处理
 * 
 * @author yilabao
 * @date 2021年2月25日
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice(basePackages = ProjectConstants.PROJECT_PACKAGE)
public class RichTextResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private static final Logger LOG = LoggerFactory.getLogger(RichTextResponseBodyAdvice.class);

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
            ServerHttpResponse response) {

        if (body == null) {
            return body;
        }

        Object dataBody = body;

        if (body instanceof AjaxResult) {
            dataBody = ((AjaxResult) body).getData();
        } else if (body instanceof ReturnVO) {
            dataBody = ((ReturnVO<?>) body).getData();
        }

        final String basePath = WebKit.getFileBasePath();

        try {
            BodyAdviceKit.resetSimpleObject(dataBody, RichText.class, new BodyAdvice() {
                @Override
                public Object getAdviceFieldValue(Object fieldValue) throws Exception {
                    return HtmlKit.getHtmlContent(String.valueOf(fieldValue), basePath);
                }
            });
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            throw new BaseException("富文本解析异常");
        }

        return body;
    }

}
